package com.programmercarl.tree;

/**
 * https://leetcode.cn/problems/path-sum/
 *
 * @author yulongtian
 * @create 2024-12-19 10:03
 */
public class Test12 {
    public static void main(String[] args) {

    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        return dfs(root, 0, targetSum);
    }

    public boolean dfs(TreeNode root, int sum, int targetSum) {
        if (root == null) {
            return false;
        }

        sum += root.val;
        if (root.left == null && root.right == null) {
            return sum == targetSum;
        }
        boolean dfs_left = dfs(root.left, sum, targetSum);
        boolean dfs_right = dfs(root.right, sum, targetSum);
        sum -= root.val;

        return dfs_left || dfs_right;
    }

}
